package com.sise.stuteaintersys.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sise.stuteaintersys.bean.protocol.NetResult;
import com.sise.stuteaintersys.locallibs.enums.FileEnum;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;


/**
 * @ClassName FileManagerController
 * @Description TODO
 * @Date 2018/12/22 12:59
 * @Version 1.0
 **/

@RestController
@RequestMapping(value = "fileManager")
public class FileManagerController {

    /**
     * 文件管理根目录
     **/
    @Value("${root.file}")
    private String root;

    /**
     * 展示文件列表
     */
    @RequestMapping("list")
    public NetResult<List<JSONObject>> list(@RequestBody JSONObject json) {
        System.out.println(root);
        try {
            // 需要显示的目录路径s
            String path = json.getString("path");
            // 返回的结果集
            List<JSONObject> fileItems = new ArrayList<>();

            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(root, path))) {

                String dateFormat = "yyyy-MM-dd HH:mm:ss";
                SimpleDateFormat dt = new SimpleDateFormat(dateFormat);
                for (Path pathObj : directoryStream) {
                    // 获取文件基本属性
                    BasicFileAttributes attrs = Files.readAttributes(pathObj, BasicFileAttributes.class);

                    // 封装返回JSON数据
                    JSONObject fileItem = new JSONObject();
                    fileItem.put("name", pathObj.getFileName().toString());

                    fileItem.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis())));
                    fileItem.put("size", attrs.size());
                    fileItem.put("type", attrs.isDirectory() ? "dir" : "file");
                    fileItems.add(fileItem);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new NetResult<>(FileEnum.FILESUCCESS.getCode(), FileEnum.FILESUCCESS.getMessage(), fileItems);
        } catch (Exception e) {
            System.err.println("获取文件列表失败！");
            e.printStackTrace();
            return new NetResult<>(FileEnum.FIELDERROR.getCode(), FileEnum.FIELDERROR.getMessage());
        }
    }

    /**
     * 文件上传
     */
    @RequestMapping("upload")
    public NetResult upload(@RequestParam("destination") String destination, HttpServletRequest request) {

        try {
            // Servlet3.0方式上传文件
            Collection<Part> parts = request.getParts();

            for (Part part : parts) {
                if (part.getContentType() != null) {
                    // 忽略路径字段,只处理文件类型
                    String path = root + destination;

                    File f = new File(path,
                            com.sise.stuteaintersys.library.utils.FileUtils.getFileName(part.getHeader("content-disposition")));
                    if (!com.sise.stuteaintersys.library.utils.FileUtils.write(part.getInputStream(), f)) {
                        throw new Exception("文件上传失败");
                    }
                }
            }
            return NetResult.netresultok();
        } catch (Exception e) {
            return new NetResult(FileEnum.FILEUPLOADERROR.getCode(), FileEnum.FILEUPLOADERROR.getMessage());
        }
    }

    /**
     * 文件下载/预览
     */
    @RequestMapping("preview")
    public void preview(HttpServletResponse response, String path) throws IOException {

        File file = new File(root, path);
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource Not Found");
            return;
        }

        /*
         * 获取mimeType
         */
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        response.setHeader("Content-disposition",
                String.format("attachment; filename=\"%s\"", URLEncoder.encode(file.getName(), "UTF-8")));
        response.setContentLength((int) file.length());

        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
            FileCopyUtils.copy(inputStream, response.getOutputStream());
        }
    }

    /**
     * 创建目录
     */
    @RequestMapping("createFolder")
    public NetResult createFolder(@RequestBody JSONObject json) {
        try {
            String newPath = json.getString("newPath");
            File newDir = new File(root + newPath);
            if (!newDir.mkdir()) {
                throw new Exception("不能创建目录: " + newPath);
            }
            return NetResult.netresultok();
        } catch (Exception e) {
            return new NetResult(FileEnum.CAGETEFOLDERERROR.getCode(), FileEnum.CAGETEFOLDERERROR.getMessage());
        }
    }

    /**
     * 复制文件或目录
     */
    @RequestMapping("copy")
    public NetResult copy(@RequestBody JSONObject json, HttpServletRequest request) {
        try {
            String newpath = json.getString("newPath");
            JSONArray items = json.getJSONArray("items");

            for (int i = 0; i < items.size(); i++) {
                String path = items.getString(i);

                File srcFile = new File(root, path);
                File destFile = new File(root + newpath, srcFile.getName());

                FileCopyUtils.copy(srcFile, destFile);
            }
            return NetResult.netresultok();
        } catch (Exception e) {
            return new NetResult(FileEnum.CONFERRER.getCode(), FileEnum.CONFERRER.getMessage());
        }
    }

    /**
     * 移动文件或目录
     */
    @RequestMapping("move")
    public NetResult move(@RequestBody JSONObject json) {
        try {
            String newpath = json.getString("newPath");
            JSONArray items = json.getJSONArray("items");

            for (int i = 0; i < items.size(); i++) {
                String path = items.getString(i);

                File srcFile = new File(root, path);
                File destFile = new File(root + newpath, srcFile.getName());

                if (srcFile.isFile()) {
                    FileUtils.moveFile(srcFile, destFile);
                } else {
                    FileUtils.moveDirectory(srcFile, destFile);
                }
            }
            return NetResult.netresultok();
        } catch (Exception e) {
            return new NetResult(FileEnum.MOVEERROR.getCode(), FileEnum.MOVEERROR.getMessage());
        }
    }

    /**
     * 删除文件或目录
     */
    @RequestMapping("remove")
    public Object remove(@RequestBody JSONObject json) {
        try {
            JSONArray items = json.getJSONArray("items");
            for (int i = 0; i < items.size(); i++) {
                String path = items.getString(i);
                File srcFile = new File(root, path);
                if (!FileUtils.deleteQuietly(srcFile)) {
                    throw new Exception("删除失败: " + srcFile.getAbsolutePath());
                }
            }
            return NetResult.netresultok();
        } catch (Exception e) {
            return new NetResult(FileEnum.REMOVEERROR.getCode(), FileEnum.REMOVEERROR.getMessage());
        }
    }

    /**
     * 重命名文件或目录
     */
    @RequestMapping("rename")
    public Object rename(@RequestBody JSONObject json) {
        try {
            String path = json.getString("item");
            String newPath = json.getString("newItemPath");

            File srcFile = new File(root, path);
            File destFile = new File(root, newPath);
            if (srcFile.isFile()) {
                FileUtils.moveFile(srcFile, destFile);
            } else {
                FileUtils.moveDirectory(srcFile, destFile);
            }
            return NetResult.netresultok();
        } catch (Exception e) {
            return new NetResult(FileEnum.RENAMEERROR.getCode(), FileEnum.RENAMEERROR.getMessage());
        }
    }

}
